﻿using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Routing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Bit.Art.Api.Conventions
{
    public class RouteConvention : IApplicationModelConvention
    {
        private readonly AttributeRouteModel _centralPrefix;

        public RouteConvention(IRouteTemplateProvider routeTemplateProvider)
        {
            _centralPrefix = new AttributeRouteModel(routeTemplateProvider);
        }

        public void Apply(ApplicationModel application)
        {
            foreach (var controller in application.Controllers)
            {
                var unmatchedSelectors = controller.Selectors.Where(x => x.AttributeRouteModel == null).ToList();
                if (unmatchedSelectors.Any())
                {
                    foreach (var action in controller.Actions)
                    {
                        //未配置的直接使用
                        var actionSelectors = action.Selectors.Where(x => x.AttributeRouteModel == null).ToList();
                        if (actionSelectors.Any())
                        {
                            actionSelectors.ForEach(a => a.AttributeRouteModel = _centralPrefix);
                            continue;
                        }

                        //已配置的
                        var hasSetActionSelectors = action.Selectors.Where(x => x.AttributeRouteModel != null).ToList();
                        if (hasSetActionSelectors.Any())
                            hasSetActionSelectors.ForEach(a =>
                            {
                                var attrModel = new AttributeRouteModel();
                                var actionTemplate = a.AttributeRouteModel.Template;
                                attrModel.Template = $"{_centralPrefix.Template.Replace("[action]", actionTemplate)}";
                                a.AttributeRouteModel = attrModel;
                            });
                    }
                }
            }
        }
    }
}
